﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bookshop
{
    public partial class Billing : Form
    {
        public Billing()
        {
            InitializeComponent();
            populate();
        }

        SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C#\MyProject\BookShopDb.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=False;");

        private void label9_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Billing_Load(object sender, EventArgs e)
        {
            UserNameLbl.Text = login.UserName;
            foreach (Control c in panel6.Controls)
            {
                c.MouseClick += (s, e2) => panel6_MouseClick(panel6, e2);
            }
            foreach (Control c in panel5.Controls)
            {
                c.MouseClick += (s, e2) => panel5_MouseClick(panel5, e2);
            }
        }

        private void populate()
        {
            Con.Open();
            string query = "select * from BookTb1";
            SqlDataAdapter adapter = new SqlDataAdapter(query, Con);
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            var ds = new DataSet();
            adapter.Fill(ds);
            BookDGV.DataSource = ds.Tables[0];
            Con.Close();
        }

        private void Reset()
        {
            BTitleTb.Text = "";
            QtyTb.Text = "";
            PriceTb.Text = "";
            BCatCb2.SelectedIndex = -1;
        }

        private void ResetBtn_Click(object sender, EventArgs e)
        {
            Reset();
            populate();
        }

        private void BCatCb2_SelectionChangeCommitted(object sender, EventArgs e)
        {
            Con.Open();
            string query = "select * from BookTb1 where BCat='" + BCatCb2.SelectedItem.ToString() + "'";
            SqlDataAdapter sda = new SqlDataAdapter(query, Con);
            SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            var ds = new DataSet();
            sda.Fill(ds);
            BookDGV.DataSource = ds.Tables[0];
            Con.Close();
        }

        private void BookDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            BTitleTb.Text = BookDGV.SelectedRows[0].Cells[1].Value.ToString();
            QtyTb.Text = "1";
            PriceTb.Text = BookDGV.SelectedRows[0].Cells[5].Value.ToString();
        }
        int uid = 0;
        private void QueryUId()
        {
            try
            {
                Con.Open();
                string query = "select UId from UserTb1 where UName=@UN ";
                SqlCommand cmd = new SqlCommand(query, Con);
                cmd.Parameters.AddWithValue("@UN", UserNameLbl.Text);
                uid = (int)cmd.ExecuteScalar();
                Con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询用户ID失败！" + ex.Message);
            }
            finally
            {
                if (Con.State == ConnectionState.Open)
                {
                    Con.Close();
                }
            }

        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(QtyTb.Text.Trim(), out int qty) || qty <= 0)
            {
                MessageBox.Show("请输入有效数值！");
            }
            else if (BTitleTb.Text == "" || PriceTb.Text == "")
            {
                MessageBox.Show("请选择您要购买的书籍！");
            }
            else
            {
                int sock = Convert.ToInt32(BookDGV.SelectedRows[0].Cells[4].Value.ToString());
                if (qty > sock)
                {
                    MessageBox.Show("库存不足");
                }
                else
                {
                    try
                    {
                        int qtynow = sock - qty;
                        float price = float.Parse(PriceTb.Text);
                        float amount = qty * price;
                        QueryUId();

                        //float amount = Convert.ToInt32(QtyTb.Text) * Convert.ToInt32(PriceTb.Text);
                        string query = "insert into BillTb1 (UId, BTitle,Qty, Amount) values(@uid,@title,@qty,@amount)";
                        Con.Open();
                        SqlCommand cmd = new SqlCommand(query, Con);
                        cmd.Parameters.AddWithValue("@uid", uid);
                        cmd.Parameters.AddWithValue("@title", BTitleTb.Text);
                        cmd.Parameters.AddWithValue("@qty", qty);
                        cmd.Parameters.AddWithValue("@amount", amount);
                        cmd.ExecuteNonQuery();

                        MessageBox.Show("购买成功！");

                        string updateQuery = "update BookTb1 set BQty=@qtynow where BTitle=@title";
                        SqlCommand ucmd = new SqlCommand(updateQuery, Con);
                        ucmd.Parameters.AddWithValue("@qtynow", qtynow);
                        ucmd.Parameters.AddWithValue("@title", BTitleTb.Text);
                        ucmd.ExecuteNonQuery();

                        Con.Close();
                        populate();
                    }
                    catch (Exception Ex)
                    {
                        MessageBox.Show("购买失败!" + Ex.Message);
                    }
                    finally
                    {
                        if (Con.State == ConnectionState.Open)
                        {
                            Con.Close();
                        }
                    }
                }

            }
        }

        private void panel6_MouseClick(object sender, MouseEventArgs e)
        {
            this.Hide();
            Billing2 obj = new Billing2();
            obj.Show();
        }

        private void panel5_MouseClick(object sender, MouseEventArgs e)
        {
            this.Hide();
            login obj = new login();
            obj.Show();
        }
    }
}
